<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>电信套餐订购系统 - 套餐管理</title>
    <!-- 引入项目现有的CSS -->
    <link rel="stylesheet" href="./css/github-markdown-light.css">
    <style>
        body {
            margin: 0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
            background-color: #f6f8fa;
            color: #1f2328;
            min-height: 100vh;
        }
        
        .container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            box-sizing: border-box;
        }
        
        .header {
            background-color: #ffffff;
            padding: 20px;
            border: 1px solid #d1d9e0;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .header h1 {
            margin: 0;
            font-size: 24px;
            color: #1f2328;
        }
        
        .tab-container {
            display: flex;
            background-color: #ffffff;
            border: 1px solid #d1d9e0;
            border-radius: 8px;
            margin-bottom: 20px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .tab {
            padding: 12px 20px;
            cursor: pointer;
            background-color: #f6f8fa;
            border-bottom: 2px solid transparent;
            transition: all 0.2s ease;
            font-weight: 500;
        }
        
        .tab.active {
            background-color: #ffffff;
            border-bottom: 2px solid #0969da;
            color: #0969da;
        }
        
        .content-container {
            background-color: #ffffff;
            padding: 20px;
            border: 1px solid #d1d9e0;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .search-filter {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            align-items: center;
        }
        
        .search-filter input,
        .search-filter select {
            padding: 8px 12px;
            border: 1px solid #d1d9e0;
            border-radius: 6px;
            font-size: 14px;
        }
        
        .search-filter button {
            padding: 8px 16px;
            background-color: #0969da;
            color: #ffffff;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
        }
        
        .search-filter button:hover {
            background-color: #0758b5;
        }
        
        .add-btn {
            padding: 8px 16px;
            background-color: #28a745;
            color: #ffffff;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
        }
        
        .add-btn:hover {
            background-color: #218838;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        
        th, td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #d1d9e0;
        }
        
        th {
            background-color: #f6f8fa;
            font-weight: 600;
        }
        
        tr:hover {
            background-color: #f6f8fa;
        }
        
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        
        .edit-btn {
            padding: 5px 10px;
            background-color: #0969da;
            color: #ffffff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .edit-btn:hover {
            background-color: #0758b5;
        }
        
        .delete-btn {
            padding: 5px 10px;
            background-color: #d73a49;
            color: #ffffff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .delete-btn:hover {
            background-color: #cb2431;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }
        
        .modal-content {
            background-color: #ffffff;
            padding: 25px;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        
        .modal-header {
            margin-bottom: 20px;
        }
        
        .modal-header h2 {
            margin: 0;
            font-size: 20px;
            color: #1f2328;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #1f2328;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 8px 12px;
            font-size: 14px;
            border: 1px solid #d1d9e0;
            border-radius: 6px;
            box-sizing: border-box;
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }
        
        .form-buttons {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        
        .confirm-btn {
            padding: 8px 16px;
            background-color: #28a745;
            color: #ffffff;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
        }
        
        .confirm-btn:hover {
            background-color: #218838;
        }
        
        .cancel-btn {
            padding: 8px 16px;
            background-color: #6c757d;
            color: #ffffff;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
        }
        
        .cancel-btn:hover {
            background-color: #5a6268;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 5px;
            margin-top: 20px;
        }
        
        .pagination button {
            padding: 5px 10px;
            border: 1px solid #d1d9e0;
            background-color: #ffffff;
            color: #1f2328;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .pagination button.active {
            background-color: #0969da;
            color: #ffffff;
            border-color: #0969da;
        }
        
        .pagination button:disabled {
            background-color: #f6f8fa;
            color: #818b98;
            cursor: not-allowed;
        }
        
        .category-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .category-card {
            background-color: #f6f8fa;
            padding: 15px;
            border-radius: 6px;
            border: 1px solid #d1d9e0;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .category-card:hover {
            background-color: #ffffff;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .category-card h3 {
            margin: 0 0 10px 0;
            font-size: 16px;
            color: #1f2328;
        }
        
        .category-card p {
            margin: 0;
            font-size: 14px;
            color: #59636e;
        }
        
        .alert {
            padding: 12px 16px;
            margin-bottom: 15px;
            border-radius: 6px;
            font-size: 14px;
        }
        
        .alert-success {
            background-color: #dafbe1;
            color: #116329;
            border: 1px solid #87d096;
        }
        
        .alert-error {
            background-color: #ffebe9;
            color: #cf222e;
            border: 1px solid #ffb0a8;
        }
        
        .alert-info {
            background-color: #e1f3fd;
            color: #0366d6;
            border: 1px solid #9cd0f8;
        }
        
        .checkbox-group {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .checkbox-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        /* 优惠信息列表样式 */
        .promotion-list {
            max-height: 80px;
            overflow-y: auto;
        }
        
        .promotion-item {
            padding: 2px 0;
            font-size: 13px;
            color: #28a745;
        }
        
        .no-promotion {
            color: #6c757d;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="tab-container">
            <div class="tab active" onclick="switchTab('packageList')">套餐列表</div>
            <div class="tab" onclick="switchTab('categoryManage')">分类管理</div>
            <div class="tab" onclick="switchTab('promotionManage')">优惠政策</div>
        </div>
        
        <!-- 套餐列表内容 -->
        <div id="packageList" class="content-container">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2 style="font-size: 1.2em;">套餐信息管理</h2>
                <div>
                    <button class="add-btn" onclick="openPackageModal('add')">添加套餐</button>
                    <button class="add-btn" onclick="openImportModal()" style="margin-left: 10px;">导入套餐</button>
                </div>
            </div>
            
            <div class="search-filter">
                <input type="text" id="packageSearch" placeholder="搜索套餐名称或ID">
                <select id="packageTargetUser">
                    <option value="">全部用户群体</option>
                    <option value="学生">学生</option>
                    <option value="商务人士">商务人士</option>
                    <option value="退休人员">退休人员</option>
                    <option value="自由职业者">自由职业者</option>
                    <option value="企业管理人员">企业管理人员</option>
                </select>
                <select id="packagePriceRange">
                    <option value="">全部价格区间</option>
                    <option value="0-50">0-50元</option>
                    <option value="50-100">50-100元</option>
                    <option value="100-200">100-200元</option>
                    <option value="200+">200元以上</option>
                </select>
                <button onclick="searchPackages()">搜索</button>
            </div>
            
            <table id="packageTable">
                <thead>
                     <tr style="font-size: 0.8em;">
                        <th>套餐ID</th>
                        <th>套餐名称</th>
                        <th>月费(元)</th>
                        <th>流量</th>
                        <th>通话时长</th>
                        <th>短信条数</th>
                        <th>网络速度</th>
                        <th>目标用户</th>
                        <th>优惠信息</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 这里将通过JavaScript动态填充 -->
                </tbody>
            </table>
            
            <div class="pagination" id="packagePagination">
                <!-- 这里将通过JavaScript动态填充 -->
            </div>
        </div>
        
        <!-- 分类管理内容 -->
        <div id="categoryManage" class="content-container" style="display: none;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2 style="font-size: 1.2em;">套餐分类管理</h2>
                <button class="add-btn" onclick="openCategoryModal('add')">添加分类</button>
            </div>
            
            <div class="category-grid" id="userTypeGrid">
                <h3>按用户群体分类</h3>
                <!-- 这里将通过JavaScript动态填充 -->
            </div>
            
            <div class="category-grid" id="priceRangeGrid">
                <h3>按价格区间分类</h3>
                <!-- 这里将通过JavaScript动态填充 -->
            </div>
        </div>
        
        <!-- 优惠政策内容 -->
        <div id="promotionManage" class="content-container" style="display: none;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2 style="font-size: 1.2em;">优惠政策管理</h2>
                <button class="add-btn" onclick="openPromotionModal('add')">添加优惠政策</button>
            </div>
            
            <div class="search-filter">
                <input type="text" id="promotionSearch" placeholder="搜索优惠名称或ID">
                <select id="promotionType">
                    <option value="">全部折扣类型</option>
                    <option value="percentage">百分比折扣</option>
                    <option value="fixed_amount">固定金额优惠</option>
                </select>
                <select id="promotionTarget">
                    <option value="">全部适用群体</option>
                    <option value="学生">学生</option>
                    <option value="新用户">新用户</option>
                    <option value="家庭用户">家庭用户</option>
                    <option value="商务人士">商务人士</option>
                    <option value="长期合约用户">长期合约用户</option>
                </select>
                <button onclick="searchPromotions()">搜索</button>
            </div>
            
            <table id="promotionTable">
                <thead>
                    <tr style="font-size: 0.8em;">
                        <th>优惠ID</th>
                        <th>优惠名称</th>
                        <th>折扣类型</th>
                        <th>折扣值</th>
                        <th>适用套餐</th>
                        <th>适用用户</th>
                        <th>有效期</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 这里将通过JavaScript动态填充 -->
                </tbody>
            </table>
            
            <div class="pagination" id="promotionPagination">
                <!-- 这里将通过JavaScript动态填充 -->
            </div>
        </div>
    </div>
    
    <!-- 套餐信息模态框 -->
    <div id="packageModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="packageModalTitle">添加套餐</h2>
            </div>
            
            <form id="packageForm">
                <div class="form-group" style="display: none;">
                    <label for="packageId">套餐ID</label>
                    <input type="text" id="packageId" name="packageId" placeholder="请输入套餐ID">
                </div>
                
                <div class="form-group">
                    <label for="packageName">套餐名称</label>
                    <input type="text" id="packageName" name="packageName" placeholder="请输入套餐名称" required>
                </div>
                
                <div class="form-group">
                    <label for="packagePrice">月费(元)</label>
                    <input type="number" id="packagePrice" name="packagePrice" placeholder="请输入月费" min="0" step="0.01" required>
                </div>
                
                <div class="form-group">
                    <label for="packageDataLimit">流量限制</label>
                    <input type="number" id="packageDataLimit" name="packageDataLimit" placeholder="请输入流量限制" min="0" required>
                </div>
                
                <div class="form-group">
                    <label for="packageDataUnit">流量单位</label>
                    <select id="packageDataUnit" name="packageDataUnit" required>
                        <option value="GB">GB</option>
                        <option value="MB">MB</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="packageCallMinutes">通话时长(分钟)</label>
                    <input type="number" id="packageCallMinutes" name="packageCallMinutes" placeholder="请输入通话时长" min="0" required>
                </div>
                
                <div class="form-group">
                    <label for="packageSmsCount">短信条数</label>
                    <input type="number" id="packageSmsCount" name="packageSmsCount" placeholder="请输入短信条数" min="0" required>
                </div>
                
                <div class="form-group">
                    <label for="packageNetworkSpeed">网络速度等级</label>
                    <select id="packageNetworkSpeed" name="packageNetworkSpeed" required>
                        <option value="基础">基础</option>
                        <option value="标准">标准</option>
                        <option value="高速">高速</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="packageFeatures">附加服务</label>
                    <div class="checkbox-group">
                        <div class="checkbox-item">
                            <input type="checkbox" id="featureVideo" name="features" value="视频会员">
                            <label for="featureVideo">视频会员</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="featureMusic" name="features" value="音乐会员">
                            <label for="featureMusic">音乐会员</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="featureHealth" name="features" value="健康服务">
                            <label for="featureHealth">健康服务</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="featureIntlRoam" name="features" value="国际漫游">
                            <label for="featureIntlRoam">国际漫游</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="featureFamily" name="features" value="家庭共享">
                            <label for="featureFamily">家庭共享</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="featureAntiFraud" name="features" value="防诈骗服务">
                            <label for="featureAntiFraud">防诈骗服务</label>
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="packageTargetUsers">目标用户群体</label>
                    <div class="checkbox-group">
                        <div class="checkbox-item">
                            <input type="checkbox" id="userStudent" name="targetUsers" value="学生">
                            <label for="userStudent">学生</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="userBusiness" name="targetUsers" value="商务人士">
                            <label for="userBusiness">商务人士</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="userRetired" name="targetUsers" value="退休人员">
                            <label for="userRetired">退休人员</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="userFreelancer" name="targetUsers" value="自由职业者">
                            <label for="userFreelancer">自由职业者</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="userManager" name="targetUsers" value="企业管理人员">
                            <label for="userManager">企业管理人员</label>
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="packageDescription">套餐描述</label>
                    <textarea id="packageDescription" name="packageDescription" placeholder="请输入套餐描述" required></textarea>
                </div>
                
                <div class="form-buttons">
                    <button type="button" class="cancel-btn" onclick="closePackageModal()">取消</button>
                    <button type="submit" class="confirm-btn">确认</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 分类管理模态框 -->
    <div id="categoryModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="categoryModalTitle">添加分类</h2>
            </div>
            
            <form id="categoryForm">
                <div class="form-group">
                    <label for="categoryType">分类类型</label>
                    <select id="categoryType" name="categoryType" required>
                        <option value="userType">用户群体</option>
                        <option value="priceRange">价格区间</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="categoryName">分类名称</label>
                    <input type="text" id="categoryName" name="categoryName" placeholder="请输入分类名称" required>
                </div>
                
                <div id="priceRangeFields" style="display: none;">
                    <div class="form-group">
                        <label for="priceMin">最低价格</label>
                        <input type="number" id="priceMin" name="priceMin" placeholder="请输入最低价格" min="0" step="0.01">
                    </div>
                    
                    <div class="form-group">
                        <label for="priceMax">最高价格</label>
                        <input type="number" id="priceMax" name="priceMax" placeholder="请输入最高价格" min="0" step="0.01">
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="categoryDescription">分类描述</label>
                    <textarea id="categoryDescription" name="categoryDescription" placeholder="请输入分类描述"></textarea>
                </div>
                
                <div class="form-buttons">
                    <button type="button" class="cancel-btn" onclick="closeCategoryModal()">取消</button>
                    <button type="submit" class="confirm-btn">确认</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 优惠政策模态框 -->
    <div id="promotionModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="promotionModalTitle">添加优惠政策</h2>
            </div>
            
            <form id="promotionForm">
                <div class="form-group">
                    <label for="promotionId">优惠ID</label>
                    <input type="text" id="promotionId" name="promotionId" placeholder="请输入优惠ID">
                </div>
                
                <div class="form-group">
                    <label for="promotionName">优惠名称</label>
                    <input type="text" id="promotionName" name="promotionName" placeholder="请输入优惠名称" required>
                </div>
                
                <div class="form-group">
                    <label for="promotionDescription">优惠描述</label>
                    <textarea id="promotionDescription" name="promotionDescription" placeholder="请输入优惠描述" required></textarea>
                </div>
                
                <div class="form-group">
                    <label for="promotionTargetPackages">适用套餐</label>
                    <div class="checkbox-group" id="packageCheckboxContainer">
                        <!-- 这里将通过JavaScript动态填充 -->
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="promotionDiscountType">折扣类型</label>
                    <select id="promotionDiscountType" name="promotionDiscountType" required>
                        <option value="percentage">百分比折扣(%)</option>
                        <option value="fixed_amount">固定金额优惠(元)</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="promotionDiscountValue">折扣值</label>
                    <input type="number" id="promotionDiscountValue" name="promotionDiscountValue" placeholder="请输入折扣值" min="0" step="0.01" required>
                </div>
                
                <div class="form-group">
                    <label for="promotionEligibility">适用用户群体</label>
                    <div class="checkbox-group">
                        <div class="checkbox-item">
                            <input type="checkbox" id="eligibilityStudent" name="eligibility" value="学生">
                            <label for="eligibilityStudent">学生</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="eligibilityNewUser" name="eligibility" value="新用户">
                            <label for="eligibilityNewUser">新用户</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="eligibilityFamily" name="eligibility" value="家庭用户">
                            <label for="eligibilityFamily">家庭用户</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="eligibilityBusiness" name="eligibility" value="商务人士">
                            <label for="eligibilityBusiness">商务人士</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="eligibilityLongTerm" name="eligibility" value="长期合约用户">
                            <label for="eligibilityLongTerm">长期合约用户</label>
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="promotionValidPeriod">有效期</label>
                    <input type="text" id="promotionValidPeriod" name="promotionValidPeriod" placeholder="请输入有效期" required>
                </div>
                
                <div class="form-buttons">
                    <button type="button" class="cancel-btn" onclick="closePromotionModal()">取消</button>
                    <button type="submit" class="confirm-btn">确认</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 确认删除模态框 -->
    <div id="confirmDeleteModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>确认删除</h2>
            </div>
            
            <p id="deleteConfirmMessage">您确定要删除此项吗？此操作不可撤销。</p>
            
            <div class="form-buttons">
                <button type="button" class="cancel-btn" onclick="closeConfirmDeleteModal()">取消</button>
                <button type="button" class="delete-btn" onclick="confirmDelete()">确认删除</button>
            </div>
        </div>
    </div>
    
    <script>
        // 环境切换开关：'dev' 开发环境（调用本地http接口），'prod' 生产环境（调用/api接口）
        const ENV_MODE = 'prod'; // 修改此值切换环境
        
        // 模拟数据 - 实际应用中应从服务器获取，包含promotionPolicyList字段
        const mockPromotions = [
            {promotionId: 'DISCOUNT001', name: '学生专享折扣', description: '针对在校学生的特别折扣优惠', targetPackages: 'P001', discountType: 'percentage', discountValue: 10.00, eligibility: '学生', validPeriod: '长期有效'},
            {promotionId: 'DISCOUNT002', name: '新用户首月优惠', description: '新用户首月享受特定套餐折扣', targetPackages: 'P001,P002,P003,P005,P007', discountType: 'fixed_amount', discountValue: 10.00, eligibility: '新用户', validPeriod: '首月有效'},
            {promotionId: 'DISCOUNT003', name: '家庭共享优惠', description: '办理家庭共享套餐享受额外折扣', targetPackages: 'P004', discountType: 'percentage', discountValue: 15.00, eligibility: '家庭用户', validPeriod: '长期有效'},
            {promotionId: 'DISCOUNT004', name: '商务人士专属优惠', description: '为商务人士提供的专属优惠活动', targetPackages: 'P002,P003', discountType: 'percentage', discountValue: 5.00, eligibility: '商务人士', validPeriod: '季度有效'},
            {promotionId: 'DISCOUNT005', name: '长期合约优惠', description: '签订一年以上合约享受额外优惠', targetPackages: 'P001,P002,P003,P004,P005,P006,P007', discountType: 'fixed_amount', discountValue: 20.00, eligibility: '长期合约用户', validPeriod: '合约期间有效'}
        ];
        
        const mockPackages = [
            {packageId: 'P001', name: '青春校园套餐', price: 39.00, dataLimit: 10, dataUnit: 'GB', callMinutes: 100, smsCount: 50, networkSpeed: '基础', features: '视频会员', targetUsers: '学生', description: '专为学生设计的经济型套餐', promotionPolicyList: [mockPromotions[0], mockPromotions[1], mockPromotions[4]]},
            {packageId: 'P002', name: '商务精英套餐A', price: 99.00, dataLimit: 20, dataUnit: 'GB', callMinutes: 300, smsCount: 100, networkSpeed: '标准', features: '视频会员,音乐会员', targetUsers: '商务人士,自由职业者', description: '适合商务人士的均衡套餐', promotionPolicyList: [mockPromotions[1], mockPromotions[3], mockPromotions[4]]},
            {packageId: 'P003', name: '商务精英套餐B', price: 129.00, dataLimit: 30, dataUnit: 'GB', callMinutes: 500, smsCount: 100, networkSpeed: '高速', features: '视频会员,音乐会员,健康服务', targetUsers: '商务人士,企业管理人员', description: '适合高需求商务人士的高端套餐', promotionPolicyList: [mockPromotions[1], mockPromotions[3], mockPromotions[4]]},
            {packageId: 'P004', name: '家庭共享套餐', price: 199.00, dataLimit: 100, dataUnit: 'GB', callMinutes: 1000, smsCount: 200, networkSpeed: '高速', features: '国际漫游,视频会员,音乐会员,家庭共享', targetUsers: '企业管理人员,商务人士', description: '适合大家庭或小企业共享的超值套餐', promotionPolicyList: [mockPromotions[2], mockPromotions[4]]},
            {packageId: 'P005', name: '银发关爱套餐', price: 69.00, dataLimit: 5, dataUnit: 'GB', callMinutes: 500, smsCount: 200, networkSpeed: '标准', features: '健康服务,防诈骗服务', targetUsers: '退休人员', description: '针对老年用户的贴心套餐', promotionPolicyList: [mockPromotions[1], mockPromotions[4]]},
            {packageId: 'P006', name: '流量至尊套餐', price: 169.00, dataLimit: 50, dataUnit: 'GB', callMinutes: 500, smsCount: 200, networkSpeed: '高速', features: '国际漫游,视频会员,音乐会员', targetUsers: '自由职业者,商务人士,企业管理人员', description: '为重度流量用户设计的套餐', promotionPolicyList: [mockPromotions[4]]},
            {packageId: 'P007', name: '基础通话套餐', price: 59.00, dataLimit: 5, dataUnit: 'GB', callMinutes: 300, smsCount: 100, networkSpeed: '基础', features: '健康服务', targetUsers: '退休人员', description: '以通话为主的经济型套餐', promotionPolicyList: [mockPromotions[1], mockPromotions[4]]}
        ];
        
        // 当前编辑的数据ID
        let currentEditId = null;
        let currentEditType = null;
        
        // 切换选项卡
        function switchTab(tabName) {
            // 隐藏所有内容
            document.getElementById('packageList').style.display = 'none';
            document.getElementById('categoryManage').style.display = 'none';
            document.getElementById('promotionManage').style.display = 'none';
            
            // 移除所有选项卡的active状态
            const tabs = document.querySelectorAll('.tab');
            tabs.forEach(tab => tab.classList.remove('active'));
            
            // 显示选中的内容和选项卡
            document.getElementById(tabName).style.display = 'block';
            
            // 为选中的选项卡添加active状态
            const activeTab = Array.from(tabs).find(tab => tab.getAttribute('onclick') === `switchTab('${tabName}')`);
            if (activeTab) {
                activeTab.classList.add('active');
            }
            
            // 初始化选中的内容
            if (tabName === 'packageList') {
                loadPackageTable();
            } else if (tabName === 'categoryManage') {
                loadCategoryGrids();
            } else if (tabName === 'promotionManage') {
                loadPromotionTable();
            }
        }
        
        // 加载套餐表格数据
        function loadPackageTable() {
            const tableBody = document.querySelector('#packageTable tbody');
            tableBody.innerHTML = '';
            
            // 从后端获取最新套餐列表数据
            const apiUrl = ENV_MODE === 'dev' 
                ? 'http://localhost:8181/ai/taocan/listTaocan' 
                : '/api/taocan/listTaocan';
                
            fetch(apiUrl)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('网络响应异常');
                        }
                        return response.json();
                    })
                    .then(data => {
                        // 保存获取的数据，供编辑时使用
                        fetchedPackages = data;
                        
                        // 清空表格内容
                        tableBody.innerHTML = '';
                        
                        // 遍历套餐数据并生成表格行
                        data.forEach(pkg => {
                        // 确保pkg有promotionPolicyList属性
                        const promotionPolicyList = pkg.promotionPolicyList || [];
                        
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${pkg.packageId}</td>
                            <td>${pkg.name}</td>
                            <td>${pkg.price.toFixed(2)}</td>
                            <td>${pkg.dataLimit} ${pkg.dataUnit}</td>
                            <td>${pkg.callMinutes} 分钟</td>
                            <td>${pkg.smsCount} 条</td>
                            <td>${pkg.networkSpeed}</td>
                            <td>${pkg.targetUsers}</td>
                            <td>
                                <div class="promotion-list">
                                    ${promotionPolicyList && promotionPolicyList.length > 0 ? 
                                        promotionPolicyList.map(promotion => {
                                            const discountText = promotion.discountType === 'percentage' ? 
                                                `${promotion.discountValue.toFixed(2)}%` : 
                                                `¥${promotion.discountValue.toFixed(2)}`;
                                            return `<div class="promotion-item">${promotion.name} (${discountText})</div>`;
                                        }).join('') : 
                                        '<span class="no-promotion">无优惠</span>'
                                    }
                                </div>
                            </td>
                            <td class="action-buttons">
                                <button class="edit-btn" onclick="editPackage('${pkg.packageId}')">编辑</button>
                                <button class="delete-btn" onclick="confirmDeletePackage('${pkg.packageId}', '${pkg.name}')">删除</button>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                    
                    // 加载分页控件
                    loadPackagePagination();
                })
                .catch(error => {
                    console.error('获取套餐列表失败:', error);
                    // alert('获取套餐列表失败，请刷新页面重试');
                    // 如果请求失败，显示mock数据作为备用
                    mockPackages.forEach(pkg => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${pkg.packageId}</td>
                            <td>${pkg.name}</td>
                            <td>${pkg.price.toFixed(2)}</td>
                            <td>${pkg.dataLimit} ${pkg.dataUnit}</td>
                            <td>${pkg.callMinutes} 分钟</td>
                            <td>${pkg.smsCount} 条</td>
                            <td>${pkg.networkSpeed}</td>
                            <td>${pkg.targetUsers}</td>
                            <td>
                                <div class="promotion-list">
                                    ${pkg.promotionPolicyList && pkg.promotionPolicyList.length > 0 ? 
                                        pkg.promotionPolicyList.map(promotion => {
                                            const discountText = promotion.discountType === 'percentage' ? 
                                                `${promotion.discountValue.toFixed(2)}%` : 
                                                `¥${promotion.discountValue.toFixed(2)}`;
                                            return `<div class="promotion-item">${promotion.name} (${discountText})</div>`;
                                        }).join('') : 
                                        '<span class="no-promotion">无优惠</span>'
                                    }
                                </div>
                            </td>
                            <td class="action-buttons">
                                <button class="edit-btn" onclick="editPackage('${pkg.packageId}')">编辑</button>
                                <button class="delete-btn" onclick="confirmDeletePackage('${pkg.packageId}', '${pkg.name}')">删除</button>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                    
                    // 加载分页控件
                    loadPackagePagination();
                });
        }
        
        // 加载套餐分页控件
        function loadPackagePagination() {
            const pagination = document.getElementById('packagePagination');
            pagination.innerHTML = '';
            
            // 简单的分页示例，实际应用中应根据总记录数和每页显示数量计算
            const pageCount = 1; // 假设只有一页
            
            // 上一页按钮
            const prevBtn = document.createElement('button');
            prevBtn.textContent = '上一页';
            prevBtn.disabled = true; // 第一页时禁用
            prevBtn.addEventListener('click', () => {/* 上一页逻辑 */});
            pagination.appendChild(prevBtn);
            
            // 页码按钮
            for (let i = 1; i <= pageCount; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.textContent = i;
                pageBtn.classList.add('active'); // 第一页为当前页
                pageBtn.addEventListener('click', () => {/* 切换页码逻辑 */});
                pagination.appendChild(pageBtn);
            }
            
            // 下一页按钮
            const nextBtn = document.createElement('button');
            nextBtn.textContent = '下一页';
            nextBtn.disabled = true; // 最后一页时禁用
            nextBtn.addEventListener('click', () => {/* 下一页逻辑 */});
            pagination.appendChild(nextBtn);
        }
        
        // 加载分类管理网格
        function loadCategoryGrids() {
            const userTypeGrid = document.getElementById('userTypeGrid');
            const priceRangeGrid = document.getElementById('priceRangeGrid');
            
            // 清空网格
            userTypeGrid.innerHTML = '<h3>按用户群体分类</h3>';
            priceRangeGrid.innerHTML = '<h3>按价格区间分类</h3>';
            
            // 模拟数据（作为备用）
            const mockUserTypeCategories = [
                {name: '学生', description: '适合学生群体的套餐', count: 1},
                {name: '商务人士', description: '适合商务人士的套餐', count: 3},
                {name: '退休人员', description: '适合退休人员的套餐', count: 2},
                {name: '自由职业者', description: '适合自由职业者的套餐', count: 2},
                {name: '企业管理人员', description: '适合企业管理人员的套餐', count: 3}
            ];
            
            const mockPriceRangeCategories = [
                {name: '0-50元', description: '经济实惠的套餐', count: 1},
                {name: '50-100元', description: '性价比高的套餐', count: 2},
                {name: '100-200元', description: '高端优质的套餐', count: 4},
                {name: '200元以上', description: '豪华尊享的套餐', count: 0}
            ];
            
            // 获取用户群体分类数据
            fetch((ENV_MODE === 'dev' ? 'http://localhost:8181/ai' : '/api') + '/taocan/getUserTypeCategories')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.code === 200 && data.data && Array.isArray(data.data)) {
                        renderUserTypeCategories(data.data);
                    } else {
                        // 使用模拟数据
                        renderUserTypeCategories(mockUserTypeCategories);
                    }
                })
                .catch(error => {
                    console.error('获取用户群体分类数据失败：', error);
                    // 使用模拟数据
                    renderUserTypeCategories(mockUserTypeCategories);
                });
            
            // 获取价格区间分类数据
            fetch((ENV_MODE === 'dev' ? 'http://localhost:8181/ai' : '/api') + '/taocan/getPriceRangeCategories')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.code === 200 && data.data && Array.isArray(data.data)) {
                        renderPriceRangeCategories(data.data);
                    } else {
                        // 使用模拟数据
                        renderPriceRangeCategories(mockPriceRangeCategories);
                    }
                })
                .catch(error => {
                    console.error('获取价格区间分类数据失败：', error);
                    // 使用模拟数据
                    renderPriceRangeCategories(mockPriceRangeCategories);
                });
            
            // 渲染用户群体分类卡片
            function renderUserTypeCategories(categories) {
                categories.forEach(category => {
                    const card = document.createElement('div');
                    card.className = 'category-card';
                    card.innerHTML = `
                        <h3>${category.name} (${category.count}个套餐)</h3>
                        <p>${category.description}</p>
                    `;
                    card.addEventListener('click', () => {
                        // 切换到套餐列表，并筛选该用户群体的套餐
                        switchTab('packageList');
                        document.getElementById('packageTargetUser').value = category.name;
                        searchPackages();
                    });
                    userTypeGrid.appendChild(card);
                });
            }
            
            // 渲染价格区间分类卡片
            function renderPriceRangeCategories(categories) {
                categories.forEach(category => {
                    const card = document.createElement('div');
                    card.className = 'category-card';
                    card.innerHTML = `
                        <h3>${category.name} (${category.count}个套餐)</h3>
                        <p>${category.description}</p>
                    `;
                    card.addEventListener('click', () => {
                        // 切换到套餐列表，并筛选该价格区间的套餐
                        switchTab('packageList');
                        document.getElementById('packagePriceRange').value = category.name.replace(/[^\d+]/g, '-').replace(/^-|-$/g, '') || '';
                        searchPackages();
                    });
                    priceRangeGrid.appendChild(card);
                });
            }
        }
        
        // 加载优惠政策表格数据
        function loadPromotionTable() {
            const tableBody = document.querySelector('#promotionTable tbody');
            tableBody.innerHTML = '';
            
            // 从后端获取最新优惠政策列表数据
            const apiUrl = ENV_MODE === 'dev' 
                ? 'http://localhost:8181/ai/taocan/listPromotions' 
                : '/api/taocan/listPromotions';
                
            fetch(apiUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常');
                    }
                    return response.json();
                })
                .then(data => {
                    // 遍历优惠政策数据并生成表格行
                    data.forEach(promotion => {
                        const discountText = promotion.discountType === 'percentage' ? 
                            `${promotion.discountValue.toFixed(2)}%` : 
                            `¥${promotion.discountValue.toFixed(2)}`;
                        
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${promotion.promotionId}</td>
                            <td>${promotion.name}</td>
                            <td>${promotion.discountType === 'percentage' ? '百分比折扣' : '固定金额优惠'}</td>
                            <td>${discountText}</td>
                            <td>${promotion.targetPackages}</td>
                            <td>${promotion.eligibility}</td>
                            <td>${promotion.validPeriod}</td>
                            <td class="action-buttons">
                                <button class="edit-btn" onclick="editPromotion('${promotion.promotionId}')">编辑</button>
                                <button class="delete-btn" onclick="confirmDeletePromotion('${promotion.promotionId}', '${promotion.name}')">删除</button>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                    
                    // 加载分页控件
                    loadPromotionPagination();
                })
                .catch(error => {
                    console.error('获取优惠政策列表失败:', error);
                    // alert('获取优惠政策列表失败，请刷新页面重试');
                    // 如果请求失败，显示mock数据作为备用
                    mockPromotions.forEach(promotion => {
                        const discountText = promotion.discountType === 'percentage' ? 
                            `${promotion.discountValue.toFixed(2)}%` : 
                            `¥${promotion.discountValue.toFixed(2)}`;
                        
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${promotion.promotionId}</td>
                            <td>${promotion.name}</td>
                            <td>${promotion.discountType === 'percentage' ? '百分比折扣' : '固定金额优惠'}</td>
                            <td>${discountText}</td>
                            <td>${promotion.targetPackages}</td>
                            <td>${promotion.eligibility}</td>
                            <td>${promotion.validPeriod}</td>
                            <td class="action-buttons">
                                <button class="edit-btn" onclick="editPromotion('${promotion.promotionId}')">编辑</button>
                                <button class="delete-btn" onclick="confirmDeletePromotion('${promotion.promotionId}', '${promotion.name}')">删除</button>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                    
                    // 加载分页控件
                    loadPromotionPagination();
                });
        }
        
        // 加载优惠政策分页控件
        function loadPromotionPagination() {
            const pagination = document.getElementById('promotionPagination');
            pagination.innerHTML = '';
            
            // 简单的分页示例，实际应用中应根据总记录数和每页显示数量计算
            const pageCount = 1; // 假设只有一页
            
            // 上一页按钮
            const prevBtn = document.createElement('button');
            prevBtn.textContent = '上一页';
            prevBtn.disabled = true; // 第一页时禁用
            prevBtn.addEventListener('click', () => {/* 上一页逻辑 */});
            pagination.appendChild(prevBtn);
            
            // 页码按钮
            for (let i = 1; i <= pageCount; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.textContent = i;
                pageBtn.classList.add('active'); // 第一页为当前页
                pageBtn.addEventListener('click', () => {/* 切换页码逻辑 */});
                pagination.appendChild(pageBtn);
            }
            
            // 下一页按钮
            const nextBtn = document.createElement('button');
            nextBtn.textContent = '下一页';
            nextBtn.disabled = true; // 最后一页时禁用
            nextBtn.addEventListener('click', () => {/* 下一页逻辑 */});
            pagination.appendChild(nextBtn);
        }
        
        // 存储从后端获取的套餐数据
        let fetchedPackages = [];
        
        // 打开套餐模态框
        function openPackageModal(mode, packageId = null) {
            const modal = document.getElementById('packageModal');
            const modalTitle = document.getElementById('packageModalTitle');
            const packageForm = document.getElementById('packageForm');
            
            // 重置表单
            packageForm.reset();
            
            // 设置模态框标题
            if (mode === 'add') {
                modalTitle.textContent = '添加套餐';
                currentEditId = null;
                document.getElementById('packageId').disabled = false;
            } else {
                modalTitle.textContent = '编辑套餐';
                currentEditId = packageId;
                document.getElementById('packageId').disabled = true;
                
                // 填充表单数据
                // 优先从已请求的数据中获取，如果没有则从mock数据中获取
                let pkg = fetchedPackages.find(p => p.packageId === packageId);
                if (!pkg) {
                    pkg = mockPackages.find(p => p.packageId === packageId);
                }
                if (pkg) {
                    document.getElementById('packageId').value = pkg.packageId;
                    document.getElementById('packageName').value = pkg.name;
                    document.getElementById('packagePrice').value = pkg.price;
                    document.getElementById('packageDataLimit').value = pkg.dataLimit;
                    document.getElementById('packageDataUnit').value = pkg.dataUnit;
                    document.getElementById('packageCallMinutes').value = pkg.callMinutes;
                    document.getElementById('packageSmsCount').value = pkg.smsCount;
                    document.getElementById('packageNetworkSpeed').value = pkg.networkSpeed;
                    document.getElementById('packageDescription').value = pkg.description;
                    
                    // 处理多选框
                    const features = pkg.features.split(',');
                    const targetUsers = pkg.targetUsers.split(',');
                    
                    // 重置所有复选框
                    document.querySelectorAll('input[name="features"]').forEach(cb => cb.checked = false);
                    document.querySelectorAll('input[name="targetUsers"]').forEach(cb => cb.checked = false);
                    
                    // 选中对应的复选框
                    features.forEach(feature => {
                        const cb = document.querySelector(`input[name="features"][value="${feature.trim()}"]`);
                        if (cb) cb.checked = true;
                    });
                    
                    targetUsers.forEach(user => {
                        const cb = document.querySelector(`input[name="targetUsers"][value="${user.trim()}"]`);
                        if (cb) cb.checked = true;
                    });
                }
            }
            
            // 显示模态框
            modal.style.display = 'flex';
        }
        
        // 关闭套餐模态框
        function closePackageModal() {
            document.getElementById('packageModal').style.display = 'none';
        }
        
        // 打开分类管理模态框
        function openCategoryModal(mode, categoryId = null) {
            const modal = document.getElementById('categoryModal');
            const modalTitle = document.getElementById('categoryModalTitle');
            const categoryForm = document.getElementById('categoryForm');
            
            // 重置表单
            categoryForm.reset();
            
            // 设置模态框标题
            if (mode === 'add') {
                modalTitle.textContent = '添加分类';
                currentEditId = null;
            } else {
                modalTitle.textContent = '编辑分类';
                currentEditId = categoryId;
                // 实际应用中这里应该根据分类ID加载数据
            }
            
            // 显示模态框
            modal.style.display = 'flex';
        }
        
        // 关闭分类管理模态框
        function closeCategoryModal() {
            document.getElementById('categoryModal').style.display = 'none';
        }
        
        // 打开优惠政策模态框
        function openPromotionModal(mode, promotionId = null) {
            const modal = document.getElementById('promotionModal');
            const modalTitle = document.getElementById('promotionModalTitle');
            const promotionForm = document.getElementById('promotionForm');
            const packageCheckboxContainer = document.getElementById('packageCheckboxContainer');
            
            // 重置表单
            promotionForm.reset();
            
            // 填充套餐复选框
            packageCheckboxContainer.innerHTML = '';
            // 使用从后端获取的套餐数据（如果有），否则使用mock数据
            const packagesToUse = fetchedPackages.length > 0 ? fetchedPackages : mockPackages;
            packagesToUse.forEach(pkg => {
                const checkboxItem = document.createElement('div');
                checkboxItem.className = 'checkbox-item';
                checkboxItem.innerHTML = `
                    <input type="checkbox" id="pkg-${pkg.packageId}" name="targetPackages" value="${pkg.packageId}">
                    <label for="pkg-${pkg.packageId}">${pkg.packageId} - ${pkg.name}</label>
                `;
                packageCheckboxContainer.appendChild(checkboxItem);
            });
            
            // 设置模态框标题
            if (mode === 'add') {
                modalTitle.textContent = '添加优惠政策';
                currentEditId = null;
                document.getElementById('promotionId').disabled = false;
                // 显示模态框
                modal.style.display = 'flex';
            } else {
                modalTitle.textContent = '编辑优惠政策';
                currentEditId = promotionId;
                document.getElementById('promotionId').disabled = true;
                
                // 从后端获取特定优惠政策的数据
                const apiUrl = ENV_MODE === 'dev' 
                    ? `http://localhost:8181/ai/taocan/listPromotions` 
                    : '/api/taocan/listPromotions';
                
                fetch(apiUrl)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('网络响应异常');
                        }
                        return response.json();
                    })
                    .then(data => {
                        // 查找特定的优惠政策
                        const promotion = data.find(p => p.promotionId === promotionId);
                        if (promotion) {
                            document.getElementById('promotionId').value = promotion.promotionId;
                            document.getElementById('promotionName').value = promotion.name;
                            document.getElementById('promotionDescription').value = promotion.description || '';
                            document.getElementById('promotionDiscountType').value = promotion.discountType;
                            document.getElementById('promotionDiscountValue').value = promotion.discountValue;
                            document.getElementById('promotionValidPeriod').value = promotion.validPeriod;
                            
                            // 处理多选框
                            const targetPackages = promotion.targetPackages ? promotion.targetPackages.split(',') : [];
                            const eligibility = promotion.eligibility ? promotion.eligibility.split(',') : [];
                            
                            // 重置所有复选框
                            document.querySelectorAll('input[name="targetPackages"]').forEach(cb => cb.checked = false);
                            document.querySelectorAll('input[name="eligibility"]').forEach(cb => cb.checked = false);
                            
                            // 选中对应的复选框
                            targetPackages.forEach(pkgId => {
                                const cb = document.querySelector(`input[name="targetPackages"][value="${pkgId.trim()}"]`);
                                if (cb) cb.checked = true;
                            });
                            
                            eligibility.forEach(user => {
                                const cb = document.querySelector(`input[name="eligibility"][value="${user.trim()}"]`);
                                if (cb) cb.checked = true;
                            });
                        }
                        
                        // 显示模态框
                        modal.style.display = 'flex';
                    })
                    .catch(error => {
                        console.error('获取优惠政策数据失败:', error);
                        alert('获取优惠政策数据失败，请刷新页面重试');
                        
                        // 如果请求失败，尝试从mock数据中获取
                        const promotion = mockPromotions.find(p => p.promotionId === promotionId);
                        if (promotion) {
                            document.getElementById('promotionId').value = promotion.promotionId;
                            document.getElementById('promotionName').value = promotion.name;
                            document.getElementById('promotionDescription').value = promotion.description || '';
                            document.getElementById('promotionDiscountType').value = promotion.discountType;
                            document.getElementById('promotionDiscountValue').value = promotion.discountValue;
                            document.getElementById('promotionValidPeriod').value = promotion.validPeriod;
                            
                            // 处理多选框
                            const targetPackages = promotion.targetPackages ? promotion.targetPackages.split(',') : [];
                            const eligibility = promotion.eligibility ? promotion.eligibility.split(',') : [];
                            
                            // 重置所有复选框
                            document.querySelectorAll('input[name="targetPackages"]').forEach(cb => cb.checked = false);
                            document.querySelectorAll('input[name="eligibility"]').forEach(cb => cb.checked = false);
                            
                            // 选中对应的复选框
                            targetPackages.forEach(pkgId => {
                                const cb = document.querySelector(`input[name="targetPackages"][value="${pkgId.trim()}"]`);
                                if (cb) cb.checked = true;
                            });
                            
                            eligibility.forEach(user => {
                                const cb = document.querySelector(`input[name="eligibility"][value="${user.trim()}"]`);
                                if (cb) cb.checked = true;
                            });
                        }
                        
                        // 显示模态框
                        modal.style.display = 'flex';
                    });
            }
        }
        
        // 关闭优惠政策模态框
        function closePromotionModal() {
            document.getElementById('promotionModal').style.display = 'none';
        }
        
        // 打开确认删除模态框
        function openConfirmDeleteModal(itemId, itemName, itemType) {
            const modal = document.getElementById('confirmDeleteModal');
            const confirmMessage = document.getElementById('deleteConfirmMessage');
            
            confirmMessage.textContent = `您确定要删除${itemType === 'package' ? '套餐' : '优惠政策'} "${itemName}"吗？此操作不可撤销。`;
            currentEditId = itemId;
            currentEditType = itemType;
            
            modal.style.display = 'flex';
        }
        
        // 关闭确认删除模态框
        function closeConfirmDeleteModal() {
            document.getElementById('confirmDeleteModal').style.display = 'none';
        }
        
        // 确认删除
        function confirmDelete() {
            if (currentEditType === 'package') {
                // 实际应用中应该发送请求到服务器删除数据
                const index = mockPackages.findIndex(pkg => pkg.packageId === currentEditId);
                if (index !== -1) {
                    mockPackages.splice(index, 1);
                    loadPackageTable();
                }
            } else if (currentEditType === 'promotion') {
                // 发送请求到服务器删除优惠政策数据
                const apiUrl = ENV_MODE === 'dev' 
                    ? `http://localhost:8181/ai/taocan/deletePromotion/${currentEditId}` 
                    : `/api/taocan/deletePromotion/${currentEditId}`;
                
                fetch(apiUrl, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        alert('删除优惠政策成功');
                        // 重新加载优惠政策列表
                        loadPromotionTable();
                        // 关闭模态框
                        closeConfirmDeleteModal();
                    } else {
                        alert('删除优惠政策失败：' + data.message);
                        closeConfirmDeleteModal();
                    }
                })
                .catch(error => {
                    console.error('删除优惠政策出错：', error);
                    alert('删除优惠政策失败，请检查网络连接');
                    closeConfirmDeleteModal();
                });
            }
        }
        
        // 确认删除套餐
        function confirmDeletePackage(packageId, packageName) {
            openConfirmDeleteModal(packageId, packageName, 'package');
        }
        
        // 确认删除优惠政策
        function confirmDeletePromotion(promotionId, promotionName) {
            openConfirmDeleteModal(promotionId, promotionName, 'promotion');
        }
        
        // 编辑套餐
        function editPackage(packageId) {
            openPackageModal('edit', packageId);
        }
        
        // 编辑优惠政策
        function editPromotion(promotionId) {
            openPromotionModal('edit', promotionId);
        }
        
        // 搜索套餐
        function searchPackages() {
            const searchTerm = document.getElementById('packageSearch').value.toLowerCase();
            const targetUser = document.getElementById('packageTargetUser').value;
            const priceRange = document.getElementById('packagePriceRange').value;
            
            const tableBody = document.querySelector('#packageTable tbody');
            tableBody.innerHTML = '';
            
            // 优先使用从后端获取的数据，如果没有则使用mock数据
            let packagesToUse = fetchedPackages.length > 0 ? fetchedPackages : mockPackages;
            let filteredPackages = packagesToUse;
            
            // 按搜索词筛选
            if (searchTerm) {
                filteredPackages = filteredPackages.filter(pkg => 
                    pkg.packageId.toLowerCase().includes(searchTerm) || 
                    pkg.name.toLowerCase().includes(searchTerm)
                );
            }
            
            // 按目标用户筛选
            if (targetUser) {
                filteredPackages = filteredPackages.filter(pkg => 
                    pkg.targetUsers.includes(targetUser)
                );
            }
            
            // 按价格区间筛选
            if (priceRange) {
                const [min, max] = priceRange.split('-').map(Number);
                if (max) {
                    filteredPackages = filteredPackages.filter(pkg => 
                        pkg.price >= min && pkg.price < max
                    );
                } else if (min === 200) {
                    filteredPackages = filteredPackages.filter(pkg => 
                        pkg.price >= min
                    );
                }
            }
            
            // 显示筛选结果
            if (filteredPackages.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = `<td colspan="10" style="text-align: center;">没有找到匹配的套餐</td>`;
                tableBody.appendChild(row);
            } else {
                filteredPackages.forEach(pkg => {
                    // 确保pkg有promotionPolicyList属性
                    const promotionPolicyList = pkg.promotionPolicyList || [];
                    
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${pkg.packageId}</td>
                        <td>${pkg.name}</td>
                        <td>${pkg.price.toFixed(2)}</td>
                        <td>${pkg.dataLimit} ${pkg.dataUnit}</td>
                        <td>${pkg.callMinutes} 分钟</td>
                        <td>${pkg.smsCount} 条</td>
                        <td>${pkg.networkSpeed}</td>
                        <td>${pkg.targetUsers}</td>
                        <td>
                            <div class="promotion-list">
                                ${promotionPolicyList && promotionPolicyList.length > 0 ? 
                                    promotionPolicyList.map(promotion => {
                                        const discountText = promotion.discountType === 'percentage' ? 
                                            `${promotion.discountValue.toFixed(2)}%` : 
                                            `¥${promotion.discountValue.toFixed(2)}`;
                                        return `<div class="promotion-item">${promotion.name} (${discountText})</div>`;
                                    }).join('') : 
                                    '<span class="no-promotion">无优惠</span>'
                                }
                            </div>
                        </td>
                        <td class="action-buttons">
                            <button class="edit-btn" onclick="editPackage('${pkg.packageId}')">编辑</button>
                            <button class="delete-btn" onclick="confirmDeletePackage('${pkg.packageId}', '${pkg.name}')">删除</button>
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
            }
        }
        
        // 搜索优惠政策
        function searchPromotions() {
            const searchTerm = document.getElementById('promotionSearch').value.toLowerCase();
            const promotionType = document.getElementById('promotionType').value;
            const promotionTarget = document.getElementById('promotionTarget').value;
            
            const tableBody = document.querySelector('#promotionTable tbody');
            tableBody.innerHTML = '';
            
            // 从后端获取最新优惠政策列表数据
            const apiUrl = ENV_MODE === 'dev' 
                ? 'http://localhost:8181/ai/taocan/listPromotions' 
                : '/api/taocan/listPromotions';
                
            fetch(apiUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常');
                    }
                    return response.json();
                })
                .then(data => {
                    let filteredPromotions = data;
                    
                    // 按搜索词筛选
                    if (searchTerm) {
                        filteredPromotions = filteredPromotions.filter(promotion => 
                            promotion.promotionId.toLowerCase().includes(searchTerm) || 
                            promotion.name.toLowerCase().includes(searchTerm)
                        );
                    }
                    
                    // 按折扣类型筛选
                    if (promotionType) {
                        filteredPromotions = filteredPromotions.filter(promotion => 
                            promotion.discountType === promotionType
                        );
                    }
                    
                    // 按适用群体筛选
                    if (promotionTarget) {
                        filteredPromotions = filteredPromotions.filter(promotion => 
                            promotion.eligibility.includes(promotionTarget)
                        );
                    }
                    
                    // 显示筛选结果
                    if (filteredPromotions.length === 0) {
                        const row = document.createElement('tr');
                        row.innerHTML = `<td colspan="8" style="text-align: center;">没有找到匹配的优惠政策</td>`;
                        tableBody.appendChild(row);
                    } else {
                        filteredPromotions.forEach(promotion => {
                            const discountText = promotion.discountType === 'percentage' ? 
                                `${promotion.discountValue.toFixed(2)}%` : 
                                `¥${promotion.discountValue.toFixed(2)}`;
                            
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td>${promotion.promotionId}</td>
                                <td>${promotion.name}</td>
                                <td>${promotion.discountType === 'percentage' ? '百分比折扣' : '固定金额优惠'}</td>
                                <td>${discountText}</td>
                                <td>${promotion.targetPackages}</td>
                                <td>${promotion.eligibility}</td>
                                <td>${promotion.validPeriod}</td>
                                <td class="action-buttons">
                                    <button class="edit-btn" onclick="editPromotion('${promotion.promotionId}')">编辑</button>
                                    <button class="delete-btn" onclick="confirmDeletePromotion('${promotion.promotionId}', '${promotion.name}')">删除</button>
                                </td>
                            `;
                            tableBody.appendChild(row);
                        });
                    }
                })
                .catch(error => {
                    console.error('获取优惠政策列表失败:', error);
                    alert('获取优惠政策列表失败，请刷新页面重试');
                    
                    // 如果请求失败，使用mock数据进行筛选
                    let filteredPromotions = mockPromotions;
                    
                    // 按搜索词筛选
                    if (searchTerm) {
                        filteredPromotions = filteredPromotions.filter(promotion => 
                            promotion.promotionId.toLowerCase().includes(searchTerm) || 
                            promotion.name.toLowerCase().includes(searchTerm)
                        );
                    }
                    
                    // 按折扣类型筛选
                    if (promotionType) {
                        filteredPromotions = filteredPromotions.filter(promotion => 
                            promotion.discountType === promotionType
                        );
                    }
                    
                    // 按适用群体筛选
                    if (promotionTarget) {
                        filteredPromotions = filteredPromotions.filter(promotion => 
                            promotion.eligibility.includes(promotionTarget)
                        );
                    }
                    
                    // 显示筛选结果
                    if (filteredPromotions.length === 0) {
                        const row = document.createElement('tr');
                        row.innerHTML = `<td colspan="8" style="text-align: center;">没有找到匹配的优惠政策</td>`;
                        tableBody.appendChild(row);
                    } else {
                        filteredPromotions.forEach(promotion => {
                            const discountText = promotion.discountType === 'percentage' ? 
                                `${promotion.discountValue.toFixed(2)}%` : 
                                `¥${promotion.discountValue.toFixed(2)}`;
                            
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td>${promotion.promotionId}</td>
                                <td>${promotion.name}</td>
                                <td>${promotion.discountType === 'percentage' ? '百分比折扣' : '固定金额优惠'}</td>
                                <td>${discountText}</td>
                                <td>${promotion.targetPackages}</td>
                                <td>${promotion.eligibility}</td>
                                <td>${promotion.validPeriod}</td>
                                <td class="action-buttons">
                                    <button class="edit-btn" onclick="editPromotion('${promotion.promotionId}')">编辑</button>
                                    <button class="delete-btn" onclick="confirmDeletePromotion('${promotion.promotionId}', '${promotion.name}')">删除</button>
                                </td>
                            `;
                            tableBody.appendChild(row);
                        });
                    }
                });
        }
        
        // 表单提交处理
        document.getElementById('packageForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 收集表单数据
            const packageId = document.getElementById('packageId').value;
            const name = document.getElementById('packageName').value;
            const price = parseFloat(document.getElementById('packagePrice').value);
            const dataLimit = parseInt(document.getElementById('packageDataLimit').value);
            const dataUnit = document.getElementById('packageDataUnit').value;
            const callMinutes = parseInt(document.getElementById('packageCallMinutes').value);
            const smsCount = parseInt(document.getElementById('packageSmsCount').value);
            const networkSpeed = document.getElementById('packageNetworkSpeed').value;
            const description = document.getElementById('packageDescription').value;
            
            // 收集多选框数据
            const features = Array.from(document.querySelectorAll('input[name="features"]:checked'))
                .map(cb => cb.value)
                .join(',');
            
            const targetUsers = Array.from(document.querySelectorAll('input[name="targetUsers"]:checked'))
                .map(cb => cb.value)
                .join(',');
            
            // 创建套餐对象
            const packageData = {
                packageId,
                name,
                price,
                dataLimit,
                dataUnit,
                callMinutes,
                smsCount,
                networkSpeed,
                features,
                targetUsers,
                description
            };
            
            // 实际应用中应该发送请求到服务器保存数据
            if (currentEditId) {
                // 编辑现有套餐，调用后端接口
                const apiUrl = ENV_MODE === 'dev' 
                    ? 'http://localhost:8181/ai/taocan/editTaocan' 
                    : '/api/taocan/editTaocan';
                    
                fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(packageData)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        alert('编辑套餐成功');
                        // 重新加载套餐列表
                        loadPackageTable();
                        // 关闭模态框
                        closePackageModal();
                    } else {
                        alert('编辑套餐失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('编辑套餐出错：', error);
                    alert('编辑套餐失败，请检查网络连接');
                });
            } else {
                // 添加新套餐，调用后端接口
                const apiUrl = ENV_MODE === 'dev' 
                    ? 'http://localhost:8181/ai/taocan/addTaocan' 
                    : '/api/taocan/addTaocan';
                    
                fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(packageData)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        alert('添加套餐成功');
                        // 重新加载套餐列表
                        loadPackageTable();
                        // 关闭模态框
                        closePackageModal();
                    } else {
                        alert('添加套餐失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('添加套餐出错：', error);
                    alert('添加套餐失败，请检查网络连接');
                });
            }
        });
        
        document.getElementById('categoryForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 收集表单数据
            const categoryType = document.getElementById('categoryType').value;
            const categoryName = document.getElementById('categoryName').value;
            const categoryDescription = document.getElementById('categoryDescription').value;
            
            // 实际应用中应该发送请求到服务器保存数据
            
            // 关闭模态框
            closeCategoryModal();
            
            // 更新分类网格
            loadCategoryGrids();
        });
        
        document.getElementById('promotionForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 收集表单数据
            const promotionId = document.getElementById('promotionId').value;
            const name = document.getElementById('promotionName').value;
            const description = document.getElementById('promotionDescription').value;
            const discountType = document.getElementById('promotionDiscountType').value;
            const discountValue = parseFloat(document.getElementById('promotionDiscountValue').value);
            const validPeriod = document.getElementById('promotionValidPeriod').value;
            
            // 收集多选框数据
            const targetPackages = Array.from(document.querySelectorAll('input[name="targetPackages"]:checked'))
                .map(cb => cb.value)
                .join(',');
            
            const eligibility = Array.from(document.querySelectorAll('input[name="eligibility"]:checked'))
                .map(cb => cb.value)
                .join(',');
            
            // 创建优惠政策对象
            const promotionData = {
                promotionId,
                name,
                description,
                targetPackages,
                discountType,
                discountValue,
                eligibility,
                validPeriod
            };
            
            // 发送请求到服务器保存数据
            if (currentEditId) {
                // 编辑现有优惠政策，调用后端接口
                const apiUrl = ENV_MODE === 'dev' 
                    ? 'http://localhost:8181/ai/taocan/editPromotion' 
                    : '/api/taocan/editPromotion';
                
                fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(promotionData)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        alert('编辑优惠政策成功');
                        // 重新加载优惠政策列表
                        loadPromotionTable();
                        // 关闭模态框
                        closePromotionModal();
                    } else {
                        alert('编辑优惠政策失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('编辑优惠政策出错：', error);
                    alert('编辑优惠政策失败，请检查网络连接');
                });
            } else {
                // 添加新优惠政策，调用后端接口
                const apiUrl = ENV_MODE === 'dev' 
                    ? 'http://localhost:8181/ai/taocan/addPromotion' 
                    : '/api/taocan/addPromotion';
                
                fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(promotionData)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        alert('添加优惠政策成功');
                        // 重新加载优惠政策列表
                        loadPromotionTable();
                        // 关闭模态框
                        closePromotionModal();
                    } else {
                        alert('添加优惠政策失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('添加优惠政策出错：', error);
                    alert('添加优惠政策失败，请检查网络连接');
                });
            }
        });
        
        // 监听分类类型变化
        document.getElementById('categoryType').addEventListener('change', function() {
            const priceRangeFields = document.getElementById('priceRangeFields');
            if (this.value === 'priceRange') {
                priceRangeFields.style.display = 'block';
            } else {
                priceRangeFields.style.display = 'none';
            }
        });
        
        // 点击模态框外部关闭模态框
        window.addEventListener('click', function(event) {
            const modals = [
                document.getElementById('packageModal'),
                document.getElementById('categoryModal'),
                document.getElementById('promotionModal'),
                document.getElementById('confirmDeleteModal')
            ];
            
            modals.forEach(modal => {
                if (event.target === modal) {
                    modal.style.display = 'none';
                }
            });
        });
        
        // 页面加载时初始化
        window.addEventListener('load', function() {
            loadPackageTable();
        });
    </script>

    <!-- 导入套餐模态框 -->
    <div id="importModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header">
                <h2>导入套餐</h2>
            </div>
            
            <div class="form-group">
                <label for="importFile">选择JSON文件</label>
                <input type="file" id="importFile" accept=".json" required>
                <p style="color: #6c757d; font-size: 14px; margin-top: 5px;">请选择符合格式要求的套餐数据JSON文件</p>
            </div>
            
            <div class="form-buttons">
                <button class="cancel-btn" onclick="closeImportModal()">取消</button>
                <button class="confirm-btn" onclick="handleFileUpload()">导入</button>
            </div>
        </div>
    </div>
    
    <script>
        // 打开导入模态框
        function openImportModal() {
            document.getElementById('importModal').style.display = 'block';
            document.getElementById('importFile').value = '';
        }
        
        // 关闭导入模态框
        function closeImportModal() {
            document.getElementById('importModal').style.display = 'none';
        }
        
        // 处理文件上传
        function handleFileUpload() {
            const fileInput = document.getElementById('importFile');
            const file = fileInput.files[0];
            
            if (!file) {
                alert('请选择一个JSON文件');
                return;
            }
            
            // 验证文件类型
            if (file.type !== 'application/json' && !file.name.endsWith('.json')) {
                alert('请选择有效的JSON文件');
                return;
            }
            
            // 显示加载状态
            const importButton = document.querySelector('#importModal .confirm-btn');
            const originalText = importButton.textContent;
            importButton.disabled = true;
            importButton.textContent = '导入中...';
            
            // 创建FormData并发送请求
            const formData = new FormData();
            formData.append('file', file);

              const apiUrl = ENV_MODE === 'dev' 
                ? 'http://localhost:8181/ai/taocan/importPackages' 
                : '/api/taocan/importPackages';

            fetch(apiUrl, {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                return response.json();
            })
            .then(data => {
                // 显示导入结果
                let message = `导入成功！\n导入套餐数：${data.importedCount}\n跳过套餐数：${data.skippedCount}`;
                
                if (data.importedPromotionCount !== undefined && data.skippedPromotionCount !== undefined) {
                    message += `\n导入优惠政策数：${data.importedPromotionCount}\n跳过优惠政策数：${data.skippedPromotionCount}`;
                }
                
                alert(message);
                
                // 刷新表格
                loadPackageTable();
                
                // 关闭模态框
                closeImportModal();
            })
            .catch(error => {
                alert('导入失败：' + error.message);
            })
            .finally(() => {
                // 恢复按钮状态
                importButton.disabled = false;
                importButton.textContent = originalText;
            });
        }
        
        // 将导入模态框添加到点击外部关闭的逻辑中
        window.addEventListener('click', function(event) {
            const importModal = document.getElementById('importModal');
            if (event.target === importModal) {
                importModal.style.display = 'none';
            }
        });
    </script>
</body>
</html>